package com.example.visitedsys.Controller;

import com.example.visitedsys.FileConfig.FastDFSClient;
import com.example.visitedsys.Shrio.Bean.ActiveUser;
import com.example.visitedsys.Shrio.Bean.ResponseBean;
import com.example.visitedsys.service.UserService;
import com.example.visitedsys.utils.FileTool;
import com.example.visitedsys.utils.MultipartFileToFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class UploadController {
    private static final Logger logger = LogManager.getLogger(UploadController.class);
    @ModelAttribute
    public void doString(){
        MDC.put("operateModuleName","文件上传模块");
    }
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private UserService userService;


    @PostMapping("/image") //new annotation since 4.3
    public ResponseBean singleFileUpload(@RequestParam("file") MultipartFile file) {
        logger.info("文件上传服务器");
        if (file.isEmpty()) {
            return ResponseBean.error("文件不存在");
        }
            // Get the file and save it somewhere
        String path= null;
        try {
            path = fastDFSClient.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseBean.success((Object) path);
    }
    /**
     * 当前登录用户更改头像
     * */
    @PostMapping("/avater") //new annotation since 4.3
    public ResponseBean changeAvater(@RequestParam("file") MultipartFile file) throws Exception {
        logger.info("用户上传更改头像");
        if (file.isEmpty()) {
            return ResponseBean.error("文件不存在");
        }
        File transferFile = MultipartFileToFile.multipartFileToFile(file);
//        if(FileTool.getFileType(transferFile)!="jpg"||FileTool.getFileType(transferFile)!="png"){
//            return ResponseBean.error("类型校验不符合");
//        }
//        logger.info("文件检验异常，请检查上传类型");
        if(FileTool.isImage(transferFile)){
            return ResponseBean.error("非图片文件");
        }
        logger.info("文件检验异常，请检查上传类型");
        // Get the file and save it somewhere
        String path= null;
        try {
            path = fastDFSClient.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ActiveUser activeUser= (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        Long userId=activeUser.getUser().getUserId();
        userService.editAvater(path,userId);
        return ResponseBean.success();
    }



}